package top.psjj.mall.comment;

import com.fasterxml.jackson.databind.ObjectMapper;
import top.psjj.mall.exception.MallExceptionEnum;

/**
 * 响应结果统一封装
 */
public class Result<T> {
    private Integer status; //状态码
    private String msg;// 响应消息
    private T data;

    private static final Integer OK_CODE = 10000;
    private static final String OK_MSG = "SUCCESS";

    public Result(Integer status, String msg, T data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }
    public Result(Integer status, String msg) {
        this.status = status;
        this.msg = msg;
    }
    public static <T> Result success(T data){
        return new Result<T>(OK_CODE,OK_MSG,data);
    }
    public static  Result success(){
        return new Result(OK_CODE,OK_MSG);
    }
    public static Result error(Integer status, String msg){
        return new Result(status,msg);
    }
    public static Result error(MallExceptionEnum mallExceptionEnum){
        return new Result(mallExceptionEnum.getStatus(),mallExceptionEnum.getMsg());
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public static void main(String[] args) throws Exception {
        //测试成功响应
        Result data = Result.success("data");
        //转json,@ResponseBody的底层就是这段代码
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(data);
        System.out.println(json);
        //测试失败数据
        Result data2 = Result.error(MallExceptionEnum.NEED_USERNAME);
        String json2 = objectMapper.writeValueAsString(data2);
        System.out.println(json2);
    }
}
